<template>
	<form-container
		:title="formData.id ? '编辑规则日志' : '增加规则日志'"
		:width="600"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="编号" name="ruleCode">
				<a-input v-model:value="formData.ruleCode" placeholder="请输入编号" allow-clear />
			</a-form-item>
			<a-form-item label="使用日期" name="usedDate">
				<a-input v-model:value="formData.usedDate" placeholder="请输入使用日期" allow-clear />
			</a-form-item>
			<a-form-item label="已使用数量" name="used">
				<a-input-number v-model:value="formData.used" :min="1" :max="100" style="width: 100%" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</form-container>
</template>

<script setup name="rulesLogForm">
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import rulesLogApi from '@/api/dev/rulesLogApi'

	// 抽屉状态
	const visible = ref(false)
	// 定义emit事件
	const emit = defineEmits({ successful: null })
	//表单
	const formRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	//提交等待
	const submitLoading = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true //显示抽屉
		//表单数据
		formData.value = {}
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
			//const param = {
			//  id: record.id
			//}
			//rulesLogApi.rulesLogDetail(param).then((data) => {
			//  formData.value = Object.assign({}, data)
			//  })
		}
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		ruleCode: [required('请输入编号')],
		used: [required('请输入已使用数量')]
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			const formDataParam = cloneDeep(formData.value)
			rulesLogApi
				.submitForm(formDataParam, formDataParam.id)
				.then(() => {
					onClose()
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>
